﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RepositoryFramework.Services;
using RepositoryFramework;
using Portal.Logic.Validators;
using Portal.Model;
using Portal.Repository;

namespace Portal.Logic.Services
{
	/// <summary>
	/// Class <see cref="UserService"/> define user service
	/// </summary>
	public class UserService : ServiceBase<IUnitOfWorkProvider<IPortalUnitOfWork>, IPortalUnitOfWork, IUser>, IUserService
	{
		#region Fields
		private readonly IUserRepository _readOnlyRepository;
		#endregion

		#region .ctor
		/// <summary>
		/// Class <see cref="UserService"/> constructor
		/// </summary>
		/// <param name="unitOfWork"></param>
		public UserService(IPortalUnitOfWorkProvider provider, IUserValidator validator)
			: base(provider, validator)
		{
			if (GetReadOnlyUnitOfWork().UserRepository == null)
			{
				throw new ArgumentNullException("UserRepository");
			}
			_readOnlyRepository = GetReadOnlyUnitOfWork().UserRepository;
		}
		#endregion

		#region Methods
		/// <summary>
		/// Add or update user
		/// </summary>
		/// <param name="user"></param>
		/// <returns>User</returns>
		public IUser AddOrUpdate(IUser user)
		{
			using (var unitOfWork = GetTransactionalUnitOfWork())
			{
				var result = AddOrUpdate(unitOfWork.UserRepository, user);
				unitOfWork.Save();
				return result;
			}
		}

		/// <summary>
		/// Add or update user
		/// </summary>
		/// <param name="user">The user</param>
		/// <param name="repository">The repository</param>
		/// <returns>User</returns>
		public IUser AddOrUpdate(IUserRepository repository, IUser user)
		{
			if (repository == null)
			{
				throw new ArgumentNullException("repository");
			}
			Validate(user);
			return repository.AddOrUpdate(user);
		}

		/// <summary>
		/// Get user by Windows logon
		/// </summary>
		/// <param name="logon"></param>
		/// <returns>User</returns>
		public IUser GetBy(string logon)
		{
			return _readOnlyRepository.GetBy(logon);
		}

		#endregion
	}
}
